package com.kehao.leetcode.jzoffer;

import org.junit.Test;

import java.util.*;

/**
 * @author Kehao.Chen
 * @version 1.0
 * @date 2022/6/28 16:26
 */
public class JZSolution035 {

    public int findMinDifference(List<String> timePoints) {
        ArrayList<String> list = new ArrayList<>();
        list.addAll(timePoints);
        list.sort((time1,time2)->{
            String[] time1Split = time1.split(":");
            String[] time2Split = time2.split(":");
            int compareHour = Integer.parseInt(time1Split[0]) - Integer.parseInt(time2Split[0]);
            if(compareHour !=0){
                return compareHour;
            }else {
                return Integer.parseInt(time1Split[1]) - Integer.parseInt(time2Split[1]);
            }
        });
        int result = Integer.MAX_VALUE;
        for (int i = 0; i < list.size(); i++) {
            int j = (i+1)%list.size();
            int distanceMinutes = getDistanceMinutes(list.get(i), list.get(j));
            result = Integer.min(distanceMinutes,result);
        }
        return result;
    }

    private int getDistanceMinutes(String time1,String time2){
        String[] time1Split = time1.split(":");
        String[] time2Split = time2.split(":");
        int hourDistance = Integer.parseInt(time2Split[0]) - Integer.parseInt(time1Split[0]);
        if(hourDistance<0) hourDistance+=24;
        return Math.abs(hourDistance*60+Integer.parseInt(time2Split[1]) - Integer.parseInt(time1Split[1]));
    }

    @Test
    public void test01(){
        List<String> timePoints = Arrays.asList("14:49","09:56","01:02");
        int minDifference = findMinDifference(timePoints);
        System.out.println(minDifference);
    }
}
